package com.dada.interceptor;

import com.alibaba.fastjson.JSON;
import com.dada.utils.ApiResponse;
import com.dada.utils.ErrorCode;
import com.dada.utils.JsonUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by zlei on 16-5-4.
 */

//@Component
public class SignInterceptor extends HandlerInterceptorAdapter {

    private static final Logger log = LoggerFactory.getLogger(SignInterceptor.class);

    private final String hashKey = "Athens";

    private List<String> ignoreUrls = new ArrayList<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String reqUrl = request.getServletPath();
        String method = request.getMethod();
        String param = "";

        String platform = request.getHeader("Platform");

        log.info("param map: " + JSON.toJSONString(request.getParameterMap()));
        Enumeration<String> enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getParameter(key);
//            value = getEncodeStr(value, method, platform);
            value = URLEncoder.encode(value).replace("+", "%20");
            param = param + "&" + key + "=" + value;
        }
        param = param.replaceFirst("&", "");

        log.info("url: " + reqUrl + ", method: " + method + ", param: " + param + ", hashKey: " + hashKey + ", platform: " + platform);

        // 如果formdata数据为空,则获取body数据
        String body = IOUtils.toString(request.getInputStream(), "UTF-8");
        log.info("body ==> " + body);
        if(param.equals("") && body != null){
            param = body;
        }

        String hash = request.getHeader("Verification-Hash");
        log.info("Verification-Hash: " + hash);

        // 不进行校验的url
        if (ignoreUrls.contains(reqUrl)) {
            return true;
        }

        // IOS 不进行签名校验 TODO
        if ("iOS".equals(platform)) {
            return true;
        }

        if (StringUtils.isNotEmpty(hash)) {
            // 不进行校验的hash值
            log.info("param + hashKey ==> " + param + hashKey);
            String md5 = DigestUtils.md5Hex(param + hashKey);
            log.info("server md5: " + md5);
            if (hash.equals(md5)) {
                return true;
            }
        }

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JsonUtils.transformObjToJson(
                ApiResponse.failed(ErrorCode.Code.SIGN_ERROR, ErrorCode.Msg.SIGN_ERROR)
        ));

        return false;
    }

    public static String getEncodeStr(String str, String reqMethod, String platform) {

        String result = "";
        if ("iOS".equals(platform)) {
            String iosGetEncodeStr = "!*'();:@&=+$¥,/?%# []{}^\\|\n \"";
            String iosPostEncodeStr = ":/?&=;+!@#$¥()',*% {}[]^\\|\n \"";

            for (int i = 0, len = str.length(); i < len; i++) {
                String charStr = String.valueOf(str.charAt(i));

                // 是中文
                boolean isZw = com.dada.utils.StringUtils.isChineseByScript(str.charAt(i));
                if (isZw) {
                    result += URLEncoder.encode(charStr);
                    continue;
                }

                // 是中文标点符号
                boolean isChinesePunctuation = com.dada.utils.StringUtils.isChinesePunctuation(str.charAt(i));
                if (isChinesePunctuation) {
                    result += URLEncoder.encode(charStr);
                    continue;
                }

                // 特殊英文字符
                String pattern;
                if ("GET".equals(reqMethod))
                    pattern = iosGetEncodeStr;
                else
                    pattern = iosPostEncodeStr;
                boolean isSpecialStr = pattern.contains(charStr);

                if (isSpecialStr) {
                    result += URLEncoder.encode(charStr);
                    continue;
                }

                result += charStr;
            }

            result = result.replace("*", "%2A");
        } else {
            result = URLEncoder.encode(str);
        }

        // 因空格会encode 成+号,为保持Android一致,改为encode为 %20
        return result.replace("+", "%20");
    }

    public void setIgnoreUrls(List<String> ignoreUrls) {
        this.ignoreUrls = ignoreUrls;
    }

    public List<String> getIgnoreUrls() {
        return ignoreUrls;
    }

    public static void main(String[] args) {

//        String a = "aa cc";
//        System.out.println(a.contains(" "));
//
//        System.out.println(URLEncoder.encode("****"));

//        List cc = JSON.parseArray("[{photoUrl: \"http://www.imdada.cn\", materialId: 2}]", InspectPhotoSimple.class);
//        System.out.println(JSON.toJSON(cc));

//        Object[] a ;

//        String a = "[\n \n]";
//        System.out.println(getEncodeStr("[\n \n]\"", "POST", "iOS"));
//        System.out.println(a.length());
    }

}
